package top.jiangqiang.qyblog.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import top.jiangqiang.qyblog.common.base.query.PageResult;
import top.jiangqiang.qyblog.common.base.response.Result;
import top.jiangqiang.qyblog.common.exception.JsonException;
import top.jiangqiang.qyblog.core.base.service.impl.BaseServiceImpl;
import top.jiangqiang.qyblog.core.domain.dto.NavAddDto;
import top.jiangqiang.qyblog.core.domain.dto.NavQueryDto;
import top.jiangqiang.qyblog.core.domain.dto.NavUpdateDto;
import top.jiangqiang.qyblog.core.domain.entity.Nav;
import top.jiangqiang.qyblog.core.domain.vo.NavVo;
import top.jiangqiang.qyblog.core.mapper.NavMapper;
import top.jiangqiang.qyblog.core.service.INavService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 导航菜单 服务实现类
 * </p>
 *
 * @author JiangQiang
 * @since 2023-05-30
 */
@Service
public class NavServiceImpl extends BaseServiceImpl<NavMapper, Nav> implements INavService {

    @Override
    public Result<PageResult<NavVo>> findByCondition(NavQueryDto navQueryDto) {
        PageResult<NavVo> page = lambdaJoinWrapper().eq(navQueryDto.getParentId() != null, Nav::getParentId, navQueryDto.getParentId())
                .like(StrUtil.isNotBlank(navQueryDto.getName()), Nav::getName, navQueryDto.getName())
                .orderByDesc(Nav::getSort)
                .page(navQueryDto.toPage(), NavVo.class);
        Map<Long, List<NavVo>> groupByParentId = getMapGroupByParentId();
        for (NavVo record : page.getRecords()) {
            List<NavVo> navVoList = groupByParentId.get(record.getId());
            if (CollUtil.isNotEmpty(navVoList)) {
                record.setChildren(navVoList);
            } else {
                record.setChildren(new ArrayList<>());
            }
        }
        return Result.ok(page);
    }

    @Override
    public Result<NavVo> getNav(Long id) {
        return Result.ok(getNavVoWithChildren(id));
    }

    @Override
    public Result<NavVo> saveNav(NavAddDto navAddDto) {
        Nav nav = lambdaQuery().eq(Nav::getPath, navAddDto.getPath()).one();
        if (nav != null) {
            throw new JsonException("导航路径不允许重复");
        }
        nav = typeConverter.convert(navAddDto, Nav.class);
        initialValue(nav);
        baseMapper.insert(nav);
        return getNav(nav.getId());
    }

    @Override
    public Result<NavVo> editNav(NavUpdateDto navUpdateDto) {
        Long navId = navUpdateDto.getId();
        if (getById(navId) == null) {
            throw new JsonException("导航菜单不存在");
        }
        Nav nav = lambdaQuery().eq(Nav::getPath, navUpdateDto.getPath()).one();
        if (nav != null && !nav.getId().equals(navId)) {
            throw new JsonException("导航路径不允许重复");
        }
        nav = typeConverter.convert(navUpdateDto, Nav.class);
        initialValue(nav);
        baseMapper.updateById(nav);
        return getNav(navId);
    }

    @Override
    public Result<Boolean> deleteNav(Long id) {
        if (lambdaQuery().eq(Nav::getParentId, id).count() != 0) {
            return Result.error("该菜单下存在子菜单，不允许删除");
        }
        baseMapper.deleteById(id);
        return Result.ok();
    }

    /**
     * 赋初始值
     *
     * @param nav
     */
    private static void initialValue(Nav nav) {
        if (nav.getHide() == null) {
            nav.setHide(false);
        }
        if (nav.getOpenStyle() == null) {
            nav.setOpenStyle(0);
        }
        if (nav.getParentId() == null) {
            nav.setParentId(0L);
        }
    }

    @NotNull
    private NavVo getNavVoWithChildren(Long id) {
        NavVo navVo = getById(id, NavVo.class);
        if (navVo == null) {
            throw new JsonException("导航菜单不存在");
        }
        Map<Long, List<NavVo>> groupByParentId = getMapGroupByParentId();
        List<NavVo> navVoList = groupByParentId.get(id);
        if (CollUtil.isNotEmpty(navVoList)) {
            navVo.setChildren(navVoList);
        } else {
            navVo.setChildren(new ArrayList<>());
        }
        return navVo;
    }

    private Map<Long, List<NavVo>> getMapGroupByParentId() {
        //所有的菜单
        List<NavVo> navVos = lambdaJoinWrapper().list(NavVo.class);
        if (CollUtil.isNotEmpty(navVos)) {
            //根据parentId进行分组，key是parentId，value是相同parentId的菜单
            Map<Long, List<NavVo>> groupByParentId = navVos.stream().collect(Collectors.groupingBy(NavVo::getParentId));
            for (NavVo navVo : navVos) {
                //关联成树形结构
                List<NavVo> navVoList = groupByParentId.get(navVo.getId());
                if (CollUtil.isNotEmpty(navVoList)) {
                    navVo.setChildren(navVoList);
                } else {
                    navVo.setChildren(new ArrayList<>());
                }
            }
            return groupByParentId;
        } else {
            return new HashMap<>();
        }
    }
}
